package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Resource
    private WmNewsMapper wmNewsMapper;
    @Resource
    private GreenTextScan greenTextScan;
    @Resource
    private FileStorageService fileStorageService;
    @Resource
    private GreenImageScan greenImageScan;
    @Resource
    private IArticleClient articleClient;
    @Resource
    private WmChannelMapper wmChannelMapper;
    @Resource
    private WmUserMapper wmUserMapper;
    @Resource
    private WmSensitiveMapper wmSensitiveMapper;


    /**
     * 自媒体文章审核
     * @param id  自媒体文章id
     */
    @Override
    @Async
    public void autoScanWmNews(Integer id) throws InvocationTargetException, IllegalAccessException, InterruptedException {

        WmNews wmNews = wmNewsMapper.selectById(id);
        if(wmNews == null){
            log.error("文章不存在，id={}",id);
            throw new RuntimeException("文章不存在");
        }
        //文章状态必须为1，即未审核状态
        if(wmNews.getStatus().equals((short)1)) {

            Map<String, Object> textsAndImages = findNewsTextAndImages(wmNews);
            boolean isSensitive=handleSensitive(textsAndImages.get("text").toString(),wmNews);
            if(!isSensitive){
                log.error("文章审核失败，id={}",id);
                return;
            }

            //阿里云审核
          /*  boolean isTextScan=handleTextScan(textsAndImages.get("text").toString(),wmNews);
            if(!isTextScan){
                log.error("文章审核失败，id={}",id);
                return;
            }*/
          /*  boolean isImageScan =  handleImageScan((List<String>) textsAndImages.get("images"),wmNews);
            if(!isImageScan){
                log.error("文章审核失败，id={}",id);
                return;
            }*/
            
            // 保存文章到app端
            ResponseResult responseResult = null;
            try {
                responseResult = saveAppArticle(wmNews);
            } catch (Exception e) {
                log.error("调用文章服务失败，文章ID: {}，错误信息: {}", id, e.getMessage());
                // 更新文章状态为审核失败
                updateWmNews(wmNews, (short) 2, "调用文章服务失败，触发降级处理");
                throw new RuntimeException("文章服务调用失败");
            }
            
            if(responseResult != null && responseResult.getCode() == 200){
                log.info("文章审核成功，id={}",id);
                wmNews.setArticleId((Long) responseResult.getData());
                updateWmNews(wmNews, (short) 9, "审核成功");
            }else{
                log.error("文章审核失败，id={}，返回结果：{}", id, responseResult);
                updateWmNews(wmNews, (short) 2, "文章审核失败，服务返回错误");
                throw new RuntimeException("文章审核失败");
            }
        }

    }

    private boolean handleSensitive(String text, WmNews wmNews) {
        boolean flag = true;

        //获取所有的敏感词
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());

        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveList);

        //查看文章中是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(text);
        if(map.size() >0){
            updateWmNews(wmNews,(short) 2,"当前文章中存在违规内容"+map);
            flag = false;
        }

        return flag;
    }

    /**
     * 审核图片
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {

        boolean flag = true;

        if(images == null || images.size() == 0){
            return flag;
        }

        //下载图片 minIO
        //图片去重
        images = images.stream().distinct().collect(Collectors.toList());

        List<byte[]> imageList = new ArrayList<>();

        for (String image : images) {
            byte[] bytes = fileStorageService.downLoadFile(image);
            imageList.add(bytes);
        }


        //审核图片
        try {
            Map map = greenImageScan.imageScan(imageList);
            if(map != null){
                //审核失败
                if(map.get("suggestion").equals("block")){
                    flag = false;
                    updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
                }

                //不确定信息  需要人工审核
                if(map.get("suggestion").equals("review")){
                    flag = false;
                    updateWmNews(wmNews, (short) 3, "当前文章中存在不确定内容");
                }
            }

        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    private ResponseResult saveAppArticle(WmNews wmNews) throws InvocationTargetException, IllegalAccessException {
        //保存app端文章
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);
        dto.setLayout(wmNews.getType());
        log.debug("BeanUtils.copyProperties之后的dto对象: {}", dto);
        log.debug("dto.getId() = {}, dto.getContent() = {}", dto.getId(), dto.getContent());

        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if(wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser != null){
            dto.setAuthorName(wmUser.getName());
        }
        if(wmNews.getArticleId()!= null){
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());
        
        // 调用文章服务保存文章
        ResponseResult responseResult = articleClient.saveArticle(dto);
        return responseResult;

    }
    /**
     * 修改文章内容
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }


    private boolean handleTextScan(String text, WmNews wmNews) {
        boolean flag = true;
        if((wmNews.getTitle()+"-"+text).length()==0){
            return flag;
        }
        try{
            Map map = greenTextScan.greeTextScan(text);
            if(map!= null){
                //失败
                if(map.get("suggestion").equals("block")){
                    flag = false;
                    wmNews.setStatus((short)2);
                    wmNews.setReason("审核失败");
                    wmNewsMapper.updateById(wmNews);
                }
                //不确定
                if(map.get("suggestion").equals("review")){
                    flag = false;
                    wmNews.setStatus((short)3);
                    wmNews.setReason("存在不确定内容");
                    wmNewsMapper.updateById(wmNews);
                }
            }
        }catch(Exception e){
            log.error("文章审核失败，id={}",wmNews.getId());
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    private Map<String,Object> findNewsTextAndImages(WmNews wmNews) {
        StringBuilder text = new StringBuilder();
        List<String> images = new ArrayList<>();
        if(wmNews.getContent() == null||wmNews.getContent().equals("")|| StringUtils.isBlank(wmNews.getContent())){
            log.error("文章内容不存在，id={}",wmNews.getId());
            throw new RuntimeException("文章内容不存在");
        }

        List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
        for(Map map:maps){
            if(map.get("type").equals("text")){
                text.append(map.get("value"));
            }
            if(map.get("type").equals("image")){
                images.add((String) map.get("value"));
            }

        }
        if(StringUtils.isNoneBlank(wmNews.getImages())){
            String[] split = wmNews.getImages().split(",");
            images.addAll(java.util.Arrays.asList(split));
        }
        Map<String,Object> result = new HashMap<>();
        result.put("text",text.toString());
        result.put("images",images);
        return result;
    }
}